/*

@Version: 1.0

  For register this mashlet, please use the following code:
  ----------------------------------------------------------
    {"version":"1.0", "sid":"MashletHub", "oid":"createMashlet", "svcVersion":"0.1",
    "params":[
        "DB_PMOE",
        {
            "name":"DB_PMOE", "type":"DB_PMOE", "title":"Deutsche Bank AMGTO InMotion",
            "description":"", "height":"540", "width":"500","properties":{}, "tags":[ ], "roles":[ ], "category":""
        }
    ]                       
  }


  Mashlet.json
  ------------------------------------------------------------

 "DB_PMOE":{
    	"type": "DB_PMOE",
        "version": "1.0",
        "title": "",
        "small-icon": "small.gif",
        "medium-icon": "medium.gif",
        "description": "This is Deutsche Bank AMGTO InMotion",
        "properties": {

        },
        "resources": {
        	"libs": {
            	"presto_ext": true
            },
            "js": [{script:"charts/FusionCharts.js"}, {"script":"DB_PMOE.js", "property":"getDeutscheBankUserName"}]

         }
    },
     

    Mashup
    ------------------------------------------------------------
    dbAddNewObjective.emml
    dbGetCategoriesMetaData.emml
    dbGetPeopleMetaData.emml
    dbGetYearMetaData.emml
    dbUpdateObjective.emml

    (first comment line where recurssion is done (circa: line 43), register, uncomment line and update emml)
    dbObjectivesChildren.emml
       
    dbObjectivesSetForWithChildren.emml

*/
Ext.QuickTips.init();

Ext.namespace("DeutscheBank");

DeutscheBank.helpURL = "http://extjs.com/products/extjs/download.php?dl=extjs22"; //PLACE HERE THE URL FOR THE HELP FILE


DeutscheBank.development = true;
DeutscheBank.devActiveUser = "devActiveUser";
DeutscheBank.devUserName = "devUserName";




DeutscheBank.instance = "";

DeutscheBank.prefix = Ext.id();

DeutscheBank.activeNode = "";

DeutscheBank.user = "";  //This is the record_id field from the T_PEOPLE table
DeutscheBank.userName = "Loading...";
DeutscheBank.userRole = "This is a User Role";

DeutscheBank.imgPath = "";

DeutscheBank.dbFormHeight = 455;
DeutscheBank.dbFormWidth = 380;

DeutscheBank.peersModeOff = ""; //This var if for controlling the boolean state of rendering or not the peers view

DeutscheBank.treeFinalArray = [];


var DB_PMOE = Class.create(Ema.Mashlet, {

    init: function() {

    },

    render: function() {

        DeutscheBank.instance = this;
 
        //Set user and roles
        DeutscheBank.user = this.args.u;
        DeutscheBank.userRole = this.args.r;

//console.log("1) User:", DeutscheBank.user);
//console.log("2) UserRole:", DeutscheBank.userRole);

        //Setting Image path
        DeutscheBank.imgPath = DeutscheBank.instance.serverUrl + "/mashlets/DB_PMOE/images/";

        var html = [

            "<div id='loginWindowCont",DeutscheBank.prefix,"'>",
                "<div id='loginWindow",DeutscheBank.prefix,"' style='width:400px;top:100px;left:250px;position:absolute'>&nbsp</div>",
            "</div>",

            "<div id='header",DeutscheBank.prefix,"' style='display:none;background:white;width:100%;height:105px'>",
                "<table>",
                "<tr>",
                    "<td>",
                        "<img style='width:100px;height:100px' src='",DeutscheBank.imgPath,"InMotion.png'",
                    "</td>",
                    "<td style='text-align:right;width:90%;vertical-align:bottom;font-weight:bold'>",
                        "<label> InMotion </label>",
                        "<label> | </label>",
                        "<label id='dateHeader",DeutscheBank.prefix,"'> aaaa</label>",

                        "<br>",

                        "<label id='userNameHeader",DeutscheBank.prefix,"'> bbb</label>",
                        "<label> | </label>",

                        "<label id='userRoleHeader",DeutscheBank.prefix,"'> </label>",
//                        "<label> | </label>",


//                        "<label> | </label>",
                    "</td>",
                    "<td>",
                        "<img style='width:100px;height:100px' src='",DeutscheBank.imgPath,"dbLogo.png'",
                    "</td>",
                "</tr>",
            "</div>",

            "<div id='body",DeutscheBank.prefix,"'>",
                "<table>",
                    "<tr>",
                        "<td style='vertical-align:top;top:100px'>",
                            "<div id='treePanel",DeutscheBank.prefix,"' style='width:400px;top:300px'>&nbsp</div>",
                        "</td>",

                        "<td style='display:none;vertical-align:top'>", //Remove display none if u want the pie graph
    //                        "<iframe SCROLLING='NO' FRAMEBORDER='no' border=0 width='505' height='35' style='position: absolute; top: 0px; left: 402px;' src='./blank.html' name='iframe'></iframe>",
                            "<div id='graphPanel",DeutscheBank.prefix,"' style='width:450px'></div>",
                        "</td>",
                    "</tr>",
                "</table>",
            "</div>"
            ];

        this.bodyEl.update(html.join(""));

        Ext.QuickTips.init();
console.log("DB Requests started...");
        //Get MEtadata
        DeutscheBank.getMetaData();

        //Loading VTypes.
        DeutscheBank.setVTypes();


        if(!DeutscheBank.development){

            DeutscheBank.showLoginWindow();
        }
        else{
            DeutscheBank.authenticate();
        }

    },

    onRefresh: function() {
        this.render();
    }

});


DeutscheBank.getDataFromPresto = function(dataObj, callback){
console.log("xx Processing request to Presto...")    
        /*
          dataObj = {
                sid:
                oid:
                params: {

                }
         }
        */
        var conn = DeutscheBank.instance.getConnection();

        var params =  dataObj.params;

        conn.request({
                sid: dataObj.sid,
                oid: dataObj.oid,
                params: params
        }, {
                onSuccess: function(response) {

                    console.log("Response:", response);

                    if(callback){

                        callback(response);
                    }
                },
            
                onFailure: function(err) {
                    console.log('failure :', err);
//                    if(!err.message)
//                        err.message = "No message error avaialble, check console"
                    Ext.MessageBox.alert("Error", "Error check the console ", err.message);
                },
                scope: this
        });
};

/*
Sets the values for the Vtypes fields validation for the app.
 */
DeutscheBank.setVTypes = function(){

    //Year
    Ext.form.VTypes["year1"] = /^[\d]{4}$/;
    Ext.form.VTypes["year"] = function(v){

        if(!Ext.form.VTypes["year1"].test(v)){
            Ext.form.VTypes["yearText"]= "Please type a valid year";
            return false;
        }
        else{
            return true;
        }
    }

    //Same set_by, set_for
    Ext.form.VTypes["sameSetBySetFor"] = function(v){

        var set_by = Ext.getCmp("personCombo"+"set_by"+ DeutscheBank.prefix).getValue();
        var set_for = Ext.getCmp("personCombo"+"set_for"+ DeutscheBank.prefix).getValue();

        if(set_by == set_for){
            Ext.form.VTypes["sameSetBySetForText"] = "Set by and Set for combo <br>options must be different"
            return false;
        }
        else{
            return true;
        }
    }

    return true

}

/*
This function retrieves information about the DB like:
- Categories Table (for categories dropdown)
- People table (for set for and set by dropdowns)
 */
DeutscheBank.getMetaData = function(){
console.log("Getting Metadata...")
    //Categories
    var dataObj = {
        sid: "dbGetCategoriesMetaData",
        oid:  "invoke",
        params: {
        }
    }
      DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.setCategories)

    //People
    var dataObj = {
        sid: "dbGetPeopleMetaData",
        oid:  "invoke",
        params: {
        }
    }
      DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.setPeople)

    //Year
    var dataObj = {
        sid: "dbGetYearMetaData",
        oid:  "invoke",
        params: {
            set_for: DeutscheBank.user
        }
    }
      DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.setYear)

    
}

DeutscheBank.setPeople = function(response){

    var peopleArray = response.response.records.record;

    if(peopleArray.constructor == Object){
        peopleArray = [peopleArray];
    }

    DeutscheBank.people = [];

    for(var i =0; i< peopleArray.length; i++){
        
        var peopleItem = peopleArray[i];
//console.log("PeopleItem:", peopleItem);
        DeutscheBank.people.push( [peopleItem.record_id, peopleItem.mail_address, peopleItem.colour]);

        //Set also the DeutscheBank.userName
        if(peopleItem.record_id == DeutscheBank.user){
            DeutscheBank.userName = peopleItem.mail_address;
        }
    }

    //Update Header
    DeutscheBank.updateHeader(); //UserName();
//    console.log("DeutscheBank.people:",DeutscheBank.people);
}

DeutscheBank.setCategories = function(response){

    var categoriesArray = response.response.records.record; //This is an array of objects: category_name has the category text

    if(categoriesArray.constructor == Object){
        categoriesArray = [categoriesArray];
    }

    DeutscheBank.categories = [];

    for(var i=0;i<categoriesArray.length; i++){

        var catItem = categoriesArray[i];
//console.log("catItem:", catItem);

        DeutscheBank.categories.push( [catItem.category_id,catItem.category_name]);
//        console.log("DeutscheBank.categories:",DeutscheBank.categories);
    }
console.log("Categories Received...")
}

DeutscheBank.setYear = function(response){

    var yearArray = response.response.records.record;

//console.log("YearrrrrrrrrrrrrrrrrrArray:", yearArray);
    
    //If yearArray is not defined, then we are almost sure that there is no info of that user, maybe he does not exists!
    if(!yearArray){
        DeutscheBank.userDataNotFound();

        return;
    }


    if(yearArray.constructor == Object){
        yearArray = [yearArray];
    }
    
    DeutscheBank.years = [];

    //Set "All Years" as first option
    DeutscheBank.years.push( ["all", "all"])    

    for(var i =0; i< yearArray.length; i++){

        var yearItem = yearArray[i];
//console.log("yearItem:", yearItem);

        if(yearItem.year.constructor != Object){  //This is not a null value

            DeutscheBank.years.push( [yearItem.year, yearItem.year]);
        }
    }
    console.log("DeutscheBank.years:",DeutscheBank.years);
}


DeutscheBank.getPeopleComboBox = function(comboPrefix, theFieldLabel){

    if(!comboPrefix) comboPrefix = Ext.id();

    // simple array store
      var store = new Ext.data.SimpleStore({
          fields: ['index', 'personMail'],
          data : DeutscheBank.people,
          sortInfo:{
              field: "personMail", direction: "ASC"
          }
      });
      var combo = new Ext.form.ComboBox({
          id:'personCombo' + comboPrefix + DeutscheBank.prefix, //("personCombo"+"set_by"+ DeutscheBank.prefix);
          store: store,
          displayField:'personMail',
          valueField:'index',
          name:comboPrefix,
          typeAhead: true,
          style:"background:#ffCC66",
          fieldLabel: theFieldLabel,
          valueNotFoundText:"value not found",
          mode: 'local',
          forceSelection: true,
          triggerAction: 'all',
          allowBlank:false,
          vtype:'sameSetBySetFor',
          selectOnFocus:true
//          applyTo: 'local-states'
      });

    return combo;

}

DeutscheBank.getCategoriesComboBox = function(comboPrefix){

    if(!comboPrefix) comboPrefix = Ext.id();

    // simple array store
      var store = new Ext.data.SimpleStore({
          fields: ['index', 'catName'],
          data : DeutscheBank.categories,
          sortInfo:{
              field: "catName", direction: "ASC"
          }
      });
      var combo = new Ext.form.ComboBox({
          id:'categoriesCombo' + comboPrefix + DeutscheBank.prefix,
          store: store,
          displayField:'catName',
          valueField:'index',
          name:'category_id',
          typeAhead: true,
          fieldLabel:"Category",
          style:"background:#ffCC66",
          valueNotFoundText:"value not found",
          mode: 'local',
          forceSelection: true,
          triggerAction: 'all',
          allowBlank:false,
          selectOnFocus:true
//          applyTo: 'local-states'
      });

    return combo;

}

DeutscheBank.getYearComboBox = function(comboPrefix){

    if(!comboPrefix) comboPrefix = Ext.id();

    // simple array store
      var store = new Ext.data.SimpleStore({
          fields: ['year','year'],
          data : DeutscheBank.years
      });
      var combo = new Ext.form.ComboBox({
          id:'yearCombo' + comboPrefix + DeutscheBank.prefix,
          store: store,
          displayField:'year',
          valueField:'year',
          typeAhead: true,
          width:55,
          fieldLabel:"Year:",
          valueNotFoundText:"value not found",
          mode: 'local',
          forceSelection: true,
          listeners:{
               select: function(combo, record, index){

                   //Get the new year and get the info for it.
                   var year = record.data.year;

                   var queryParams ={
                       year: year
                   };

                   DeutscheBank.updateTree( queryParams)

                }
          },
          triggerAction: 'all',
//          emptyText:'Select a state...',
          selectOnFocus:true
//          applyTo: 'local-states'
      });

    return combo;

}

DeutscheBank.getYesNoComboBox = function(comboPrefix, label){

    if(!comboPrefix) comboPrefix = Ext.id();

    // simple array store
      var store = new Ext.data.SimpleStore({
          fields: ['letter','text'],
          data : [["n","NO"],["y","YES"]]
      });
      var combo = new Ext.form.ComboBox({
          id:'yesNoCombo' + comboPrefix + DeutscheBank.prefix,
          store: store,
          displayField:'text',
          valueField:'letter',
          typeAhead: true,
          width:65,
          fieldLabel:label,
          style:"background:#ffCC66",
          valueNotFoundText:"value not found",
          mode: 'local',
          forceSelection: true,
          triggerAction: 'all',
            allowBlank:false,
          selectOnFocus:true
//          applyTo: 'local-states'
      });

    return combo;

}


DeutscheBank.updateHeader = function(){

    Ext.get("header" +DeutscheBank.prefix).show();

    DeutscheBank.updateHeaderDate();

    DeutscheBank.updateHeaderUserName();

}

DeutscheBank.updateHeaderDate = function(){

    var theDate = new Date();
//    theDate= theDate.toString().substring(0, 15);
    theDate = theDate.format('F j, Y, g:i a');  //January 10, 2007, 3:05 pm

    var dateHeader = Ext.get("dateHeader" +DeutscheBank.prefix);
    dateHeader.dom.innerHTML = theDate;

    DeutscheBank.updateHeaderUserName();
}

DeutscheBank.updateHeaderUserName = function(){

    var userNameLabel = Ext.get("userNameHeader" +DeutscheBank.prefix);

    var userNameHeaderText = DeutscheBank.userName;

    userNameLabel.dom.innerHTML = userNameHeaderText;
//console.log(": USERNAME updated in header :", userNameLabel.dom.innerHTML)

    //Section for User Role

    var userRoleLabel = Ext.get("userRoleHeader" + DeutscheBank.prefix);

    userRoleLabel.dom.innerHTML = DeutscheBank.userRole;
}


DeutscheBank.showLoginWindow = function(){
         
    var loginPanel = new Ext.form.FormPanel({
        id: 'loginPanel' + DeutscheBank.prefix,
        width:300,
        height:130,
        title:'Deutshche Bank Login',
        bodyStyle:'padding:15px 15px 0',
        buttonAlign:'right',
        items:[{
            xtype:'textfield',
            fieldLabel:'User Name',
            value:"sean.kelley@db.com",
            id: 'userName' + DeutscheBank.prefix
        },{
            xtype:'textfield',
            fieldLabel:'Password',
             inputType:'password',              
            id: 'password' + DeutscheBank.prefix
        }
        ,{
            xtype:'button',
            text:'Login',
            id:'login' + DeutscheBank.prefix,
            handler: DeutscheBank.authenticate
        }
        ]
    });

    loginPanel.render('loginWindow' + DeutscheBank.prefix)

    //Key map for enter
     var map = new Ext.KeyMap( 'loginPanel' + DeutscheBank.prefix, {
            key: Ext.EventObject.ENTER, //13,
            fn: DeutscheBank.authenticate
        });



};

DeutscheBank.hideLoginWindow = function(){

//    var cont = Ext.get("loginWindowCont"+DeutscheBank.prefix);
//    cont.setVisibilityMode(Element.DISPLAY);
//    cont.setVisible(false)

    var cont = document.getElementById("loginWindowCont"+DeutscheBank.prefix);

    cont.style.display = "none";
}


DeutscheBank.authenticate = function(){

    var fakePass = "dbank";
    var pass = "";

    if(!DeutscheBank.development){

        var user = Ext.getCmp("userName" + DeutscheBank.prefix).getValue();

        pass = Ext.getCmp("password" + DeutscheBank.prefix).getValue();
//console.log("User:",user);
//console.log("pass:",pass);
        DeutscheBank.activeUser = user;

        DeutscheBank.userName = getDeutscheBankUserName();

    }
    else{                           
        pass = fakePass;

        DeutscheBank.activeUser = DeutscheBank.devActiveUser;

        DeutscheBank.userName = DeutscheBank.userName;

    }



    if(pass == fakePass){


        DeutscheBank.updateTree();


            DeutscheBank.hideLoginWindow();

            DeutscheBank.updateHeader();

    }

    else{
        Ext.MessageBox.alert("Failure", "Incorrect Login, please try again")

        var pass = Ext.getCmp("password" + DeutscheBank.prefix).setValue("");
    }



}


DeutscheBank.updateTree = function( year, questionTwo, showPeers){

    var treeExists = Ext.getCmp('myTree' + DeutscheBank.prefix);
    if(treeExists){
        console.log("Tree EXISTS... FINISH HIM!!!!");

        treeExists.destroy();

        //Reset the array that holds the tree in json string format.
        DeutscheBank.treeFinalArray=[];
    }

    var data = {};

    var mashupName = "dbObjectivesSetForWithChildren";

    //If there are values on queryParams, its because we want to query this with special values (like year for example) /Americo
    if(year){
console.log("Por year ::", year)
        if( year == 'all'){
console.log("Por year, Pero all")
            //When 'all' is on the year combo
            data = {
                sid: mashupName,
                oid:'invoke',
                params:{
                    setFor: DeutscheBank.user
                }

            };

        }
        else{
console.log("Por year specfic")            
            //Special case where we send year
            data = {
                sid: mashupName,
                oid:'invoke',
                params:{
                    setFor: DeutscheBank.user,
                    year: queryParams.year
                }

            };
        }

    }

    else if( questionTwo){
        //For calling the mashup: dbObjectivesSetForWithTree
        data = {
            sid: questionTwo.mashup,
            oid:'invoke',
            params:{
                iRecordId: questionTwo.iRecordId
            }

        };
    }

    //This will call the tree for Sean Kelly and with the help of ActiveNode it will expand the node where was when he click the show peers button
    else if (showPeers){

console.log("Showwww Peersssssss")
        data = {
            sid: mashupName,
            oid:'invoke',
            params:{
                setFor: "6208089"//DeutscheBank.user//"6208089" //"1200477" //"7042941"//Master user
            }

        };

    }

    else{
        //When 'all' is on the year combo
console.log("NORMALLLLLLLLLLLLLLLLLLL")
        data = {
            sid: mashupName,
            oid:'invoke',
            params:{
                setFor: DeutscheBank.user//"6208089" //"1200477" //"7042941"//Master user
            }

        };
    }

        
    DeutscheBank.getDataFromPresto( data, DeutscheBank.createTree );
}
                               

DeutscheBank.createTree = function( response){
//console.log("Create Treeeeeeeee");
    //Tree Generation
    var treeData = "";
    var expandNodes ="";

    if(response.sid == "dbObjectivesSetForWithTree"){
        //Case for Question 2
        treeData = response.response.root.record;   //This is an array
        expandNodes = true;

     }else{
        //Case for Question 1
         treeData = response.response.records.record;   //This is an array
     }

console.log("This is treeData:", treeData);

    //If treeData is empty, then no info associated with this user was found.
    if(!treeData){

        DeutscheBank.userDataNotFound();

        return;
    }
    //If only 1 element is comming back to the clinet (presto bug) convert it to an array
    else if(treeData.constructor == Object){
console.log("Converting treeData into an array for func: convertToTreeChildrenFormat")        
        treeData = [treeData]        
    }

    var finalData = convertToTreeChildrenFormat( treeData);
//console.log("finalData:", finalData);
    finalData = eval(finalData);
//console.log("finalData:", finalData);


    DeutscheBank.renderTree(finalData, expandNodes);

    /*****
     * Functions for recursively creating the tree
     */
    function convertToTreeChildrenFormat( data){
//console.log("haciendo un push de AMEY:[")
        DeutscheBank.treeFinalArray.push("ame:[")
            for(var i = 0; i < data.length;i++){

                iterateOverParentNode( data[i]);
                DeutscheBank.treeFinalArray.push(",");
            }
            DeutscheBank.treeFinalArray.pop();

        DeutscheBank.treeFinalArray.push("]")

        return DeutscheBank.treeFinalArray.join("");
        }


    
    function iterateOverParentNode(node){

        var theText='<span style="background-color:'+node.colour+'">&nbsp&nbsp</span> ' + node.objective_summary+ "("+ node.mail_address +")"; //Set color here
        var theListeners='click:'+ click + ', contextmenu:' +rightClick + ', dblclick:'+ dblClick + ', expand:' + expand;      // event: function, event2:fucntion2...
//        var theListeners='click:'+singleClick +',  contextmenu:' +rightClick;      // event: function, event2:fucntion2...

        //Make sure that there are no fields null (which are  [Object object])
        node.category_id = node.category_id.constructor == Object ? "" : node.category_id;
        node.inserted_by = node.inserted_by.constructor == Object ? "" : node.inserted_by;
        node.master_id = node.master_id.constructor == Object ? "" : node.master_id;
        node.objective_details = node.objective_details.constructor == Object ? "" : node.objective_details;
        node.objective_id = node.objective_id.constructor == Object ? "" : node.objective_id;
        node.objective_summary = node.objective_summary.constructor == Object ? "" : node.objective_summary;
        node.private_objective = node.private_objective.constructor == Object ? "" : node.private_objective;
        node.set_by = node.set_by.constructor == Object ? "" : node.set_by;
        node.set_for = node.set_for.constructor == Object ? "" : node.set_for;
        node.updated_by = node.updated_by.constructor == Object ? "" : node.updated_by;
        node.year = node.year.constructor == Object ? "" : node.year;
        node.colour = node.colour.constructor == Object ? "" : node.colour;
        node.leaf_ubr = node.leaf_ubr.constructor == Object ? "" : node.leaf_ubr;
        node.mail_address = node.mail_address.constructor == Object ? "" : node.mail_address;

//console.log("node.date_accepted:#",node.date_accepted,"# :: node.date_accepted.constructor:", node.date_accepted.constructor)
        //Date accepted
        if( node.date_accepted.constructor == Object || node.date_accepted == ""){
            node.date_accepted = "(empty)";
        }
        else{
            node.date_accepted = node.date_accepted.substr(0,10);

            //format Date
            var dt = Date.parseDate( node.date_accepted, "Y-m-d");    //formate comming from mashup
            node.date_accepted = dt.format('d-M-y');  //this is date format for:   dd-mmm-YYYY e.g., 01-Jun-2008
        }
        //Date Inserted
        if( node.date_inserted.constructor == Object || node.date_inserted == ""){
            node.date_inserted = "(empty)";
        }
        else{
            node.date_inserted = node.date_inserted.substr(0,10);

            //format Date
            var dt = Date.parseDate( node.date_inserted, "Y-m-d");
            node.date_inserted = dt.format('d-M-y');
        }
        //Date updated
        if( node.date_last_updated.constructor == Object || node.date_last_updated == ""){
            node.date_last_updated = "(empty)";
        }
        else{
            node.date_last_updated = node.date_last_updated.substr(0,10);

            //format Date
            var dt = Date.parseDate( node.date_last_updated, "Y-m-d");
            node.date_last_updated = dt.format('d-M-y');
        }


        var theAttributes=[
            ['category_id:"'], [node.category_id],['",'],
            ['date_accepted:"'], [node.date_accepted],['",'],
            ['date_inserted:"'], [node.date_inserted],['",'],
            ['date_last_updated:"'], [node.date_last_updated],['",'],
            ['inserted_by:"'], [node.inserted_by],['",'],
            ['master_id:"'], [node.master_id],['",'],
            ['objective_details:"'],[node.objective_details],['",'],
            ['objective_id:"'], [node.objective_id],['",'],
            ['objective_summary:"'], [node.objective_summary],['",'],
            ['private_objective:"'],[node.private_objective],['",'],
            ['set_by:"'], [node.set_by],['",'],
            ['set_for:"'], [node.set_for],['",'],
            ['updated_by:"'], [node.updated_by],['",'],
            ['year:"'], [node.year],['",'],
            ['colour:"'], [node.colour],['",'],
            ['leaf_ubr:"'], [node.leaf_ubr],['",'],
            ['mail_address:"'], [node.mail_address],['"']
        ].join("");
        
        var hasChildren = "";
//console.log("node id:", node.objective_id,"Children: ",node.children);
        if( node.children){
            hasChildren = node.children.record;  //This changed since now every child has a <record> tag.
        }
        
        //To Fix issue of only 1 objective that Presto sends as an object istead of an Array (Added on 18-Aug-08)
        if(hasChildren && hasChildren.constructor == Object){
            hasChildren = [hasChildren];
        }

        //Base case
        if(!hasChildren){
//			console.log("Hi, i am node: ", node.objective_id, ": I dont have children :(");

            //PRIVATE OBJECTIVE
            if(node.private_objective == 'y'){
//console.log("Found a private objective : ", node.objective_id);
//                //Check if the userName can see this private objective if userName = setFor || setBy
                if( DeutscheBank.user == node.set_by || DeutscheBank.user == node.set_for){
//console.log("Yes... I would definetevly see this private objective");
               
                    //User can see this node (same line of code as in Public Objective)
                    var iconStr ="";

                    if(node.master_id==""){
                        iconStr = "icon:'"+ DeutscheBank.imgPath + "user_suit.png',";
                    }

                    DeutscheBank.treeFinalArray.push("{text:'"+ theText +"', leaf:'true',"+ iconStr +" attributes:{"+theAttributes+"}, listeners:{"+theListeners+"}, qtip:'"+ node.objective_details +"'}");

                }
                else{
//console.log("No... I cant see this Private objective");
                    //User CANT SEE THIS NODE!
//                    var theText='<span style="background-color:'+node.colour+'">&nbsp&nbsp</span> ' + node.objective_summary+ "("+ node.mail_address +")";
//                    var privateText = "Private Objective " + node.objective_id;
                      var privateText= '<span style="background-color:'+node.colour+'">&nbsp&nbsp</span> Private Objective '+ node.objective_id +' (' + node.mail_address +')';
                    DeutscheBank.treeFinalArray.push("{text:'"+ privateText +"', leaf:'true', attributes:{}, qtip:'This is a private objective'}");
                }
            }

            //PUBLIC OBJECTIVE
            else{

                var iconStr ="";

                if(node.master_id==""){
                    iconStr = "icon:'"+ DeutscheBank.imgPath + "user_suit.png',";
                }

                DeutscheBank.treeFinalArray.push("{text:'"+ theText +"', leaf:'true',"+ iconStr +" attributes:{"+theAttributes+"}, listeners:{"+theListeners+"}, qtip:'"+ node.objective_details +"'}");

            }


//console.log(DeutscheBank.treeFinalArray.join(""));
        }

		//normal case
		else{
//		console.log("Hi, i am node: ", node.objective_id, ":: I have children! : ", node );

            //Private Objective
            if(node.private_objective == 'y'){

                //Check if the userName can see this private objective if userName = setFor || setBy
                if( DeutscheBank.user == node.set_by || DeutscheBank.user == node.set_for){
                    //User can see this node, same line as Public Objective in else case
                    DeutscheBank.treeFinalArray.push("{text:'"+ theText +"', icon:'"+DeutscheBank.imgPath+"user_suit.png', iconCls:'imagesAccod', attributes:{"+theAttributes+"}, listeners:{"+theListeners+"}, qtip:'"+node.objective_details+"', children:[ ");
                }
                else{
                    //Then it is private!
//                    var privateText = "Private Objective " + node.objective_id;
                    var privateText= '<span style="background-color:'+node.colour+'">&nbsp&nbsp</span> Private Objective '+ node.objective_id + ' (' + node.mail_address +')';
                    DeutscheBank.treeFinalArray.push("{text:'"+ privateText +"', disabled:true, icon:'"+DeutscheBank.imgPath+"user_suit.png', iconCls:'imagesAccod', attributes:{}, qtip:'This is a private objective', children:[ ");
                }
            }
            //Public objective
            else{
                DeutscheBank.treeFinalArray.push("{text:'"+ theText +"', icon:'"+DeutscheBank.imgPath+"user_suit.png', iconCls:'imagesAccod', attributes:{"+theAttributes+"}, listeners:{"+theListeners+"}, qtip:'"+node.objective_details+"', children:[ ");
            }

    //console.log(DeutscheBank.treeFinalArray.join(""));
    //console.log("hasChildren:",hasChildren, "  :: ", hasChildren.length);

            for(var i=0;i<hasChildren.length;i++){
                var childrenCode = iterateOverParentNode(hasChildren[i]);
                DeutscheBank.treeFinalArray.push(",");
            }
            DeutscheBank.treeFinalArray.pop();
            DeutscheBank.treeFinalArray.push("]}");
		}
	}
    
    /**
     * Functions for TreeNodes
     */

    function click(node, e){
//Todo clear tree selections (or at least this node)
//        var myTree = Ext.getCmp("myTree" + DeutscheBank.prefix);
//        var selModel = myTree.getSelectionModel();
//
//        var nodeSelected = selModel.selNode;
//
//        if(nodeSelected){
//            selModel.clearSelections();
//console.log("yaaaaaaa limpiando selecciones")
//        }

    }

    function expand(node, deep, anim){

        //If CurrentUser is not Topdog, then refresh the tree with topdog query and open the branch where this objective lives.

        if(DeutscheBank.userRole == "topdog" || DeutscheBank.peersModeOff){

            node.expandChildNodes(true);
        }
        else{

            DeutscheBank.mask(" Updating tree view please wait...", 6000, false);

            DeutscheBank.peersModeOff = true;

            //Set ActiveNode
            DeutscheBank.getActiveNodeData(node);

            DeutscheBank.updateTree(null, null, node);

        }



    }

    function rightClick(node, e){
//        Ext.MessageBox.alert("right", "rightttttttttt")
        DeutscheBank.showNodeDetailsWindow(node, e)
    }

    function dblClick(node, e){


        var iRecordId = node.attributes.attributes.set_for
//console.log("iRecordId:", iRecordId);

        var questionTwo ={
            mashup: 'dbObjectivesSetForWithTree',
            iRecordId: iRecordId
        }

        DeutscheBank.updateTree(null, questionTwo)

        DeutscheBank.mask("Loading...", 2000, false);

    }
};


DeutscheBank.renderTree = function(treeInArray, expandNodes){

    //Tree Creation
    var yearCombo = DeutscheBank.getYearComboBox("yearCombo");

    var myTree = new Ext.tree.TreePanel({
        id:'myTree' + DeutscheBank.prefix,
        useArrows:true,
        autoScroll:true,
        animate:true,
        width:563,
//        enableDD:true,
        containerScroll:true,
        autoHeight:true,
        loader: new Ext.tree.TreeLoader()
    });

    //Sort the nodes on the tree
    new Ext.tree.TreeSorter(myTree, {folderSort:true});

    var root = new Ext.tree.AsyncTreeNode({
        text: DeutscheBank.userName,
        draggable:false,
        id:'rootNode' + DeutscheBank.prefix,
        expanded:true,
        children: treeInArray
    });

    myTree.setRootNode( root);


    var treeContainerPanelExists = Ext.getCmp('treeContainerPanel' + DeutscheBank.prefix);
    if(!treeContainerPanelExists){
        //Tree Panel container not exists, create it.
        var treeContainerPanel= new Ext.Panel({
            id:'treeContainerPanel' + DeutscheBank.prefix,
            width:565,
            height:380,
            autoScroll: true,
            title: DeutscheBank.userName + ' - Objectives Tree View',
//            bbar: [
//                {
//                    xtype:'button',
//                    text:'Help',
//                    icon:DeutscheBank.imgPath +'help.png',
//                    cls:'x-btn-text-icon',
//                    handler: function(){
//
//                    }
//                }
//            ],
            tbar:[
                 yearCombo,
    //        {
    //            xtype:'button',
    //            text:'Home',
    //            icon:DeutscheBank.imgPath+'application_home.png',
    //            cls:'x-btn-text-icon',
    //            handler: function(){
    //                Ext.MessageBox.alert("Deutsche Bank - Prototype", "Clicking on the home button will show the main view for the current user, refreshing both the tree and the pie view")
    //            }
    //        },
              "-",
            {
                xtype:'button',
                text:'Add',
                icon:DeutscheBank.imgPath+'add.png',
                cls:'x-btn-text-icon',
                tooltip:'Adds a new objective, if an objective its preselected, the new objective will be added to the selected objective.',
                handler: function(){

                    var myTree = Ext.getCmp("myTree" + DeutscheBank.prefix);
                    var selModel = myTree.getSelectionModel();

                    var nodeSelected = selModel.selNode;
    console.log("selModel:", selModel.selNode);

//                    DeutscheBank.showNewObjectiveWindow(nodeSelected);
                    DeutscheBank.showActionWindow(nodeSelected);
                }
            },
                "-",

//            {
//                xtype:'button',
//                text:'Delete',
//                icon:DeutscheBank.imgPath+'delete.png',
//                cls:'x-btn-text-icon',
//                tooltip:'Deletes the selected objective',
//                handler: function(){
//
//                    var myTree = Ext.getCmp("myTree" + DeutscheBank.prefix);
//                    var selModel = myTree.getSelectionModel();
//
//                    var nodeSelected = selModel.selNode;
//
//                    DeutscheBank.deleteObjectiveNode(nodeSelected);
//                }
//            },
//                "-",
            {
                xtype:'button',
                text:'Expand All',
                icon:DeutscheBank.imgPath+'arrow_out.png',
                cls:'x-btn-text-icon',
                tooltip:'Shows an expanded view of all the objectives and sub objectives.',
                handler: function(){
//                    myTree.expandAll();  //This did not work the second time (when refresh) probably a mashlet bug /Americo

                    var myTree = Ext.getCmp('myTree' + DeutscheBank.prefix);
                    var myRoot = myTree.getRootNode();

                    var data = myRoot.childNodes

                    for(var i =0; i< data.length; i++){

                        var node = data[i];
                        node.expand(true);
                    }
                    
                }
            },
//                "-",
//            {
//                xtype:'button',
//                text:'Show Peers',
//                icon:DeutscheBank.imgPath+'sitemap_color.png',
//                tooltip:'Shows the peer objectives and its sub-objectives of the selected node.',
//                cls:'x-btn-text-icon',
//                handler: function(){
//
//                    //Get Selected Node
//                    var myTree = Ext.getCmp("myTree" + DeutscheBank.prefix);
//                    var selModel = myTree.getSelectionModel();
//
//                    var nodeSelected = selModel.selNode;
//
//
//                    if(nodeSelected){
//                        DeutscheBank.mask(" Updating tree view please wait...", 3000, false);
//
//                        DeutscheBank.peersModeOff = true;
//
//                        //Set ACtive node
//                        DeutscheBank.getActiveNodeData(nodeSelected);
//
//                        DeutscheBank.updateTree(null, null, true);
//                        //Ask for tree for Sean Kelly and it will expand on the selected node.
//
//                    }
//                    else{
//                        DeutscheBank.mask("Please select first an objective in order to show peer objectives", 4000, true)
//                    }
//
//
//                }
//            },
//           {
//                xtype:'button',
//                text:'Collapse All',
//                icon:DeutscheBank.imgPath+'sitemap.png',
//                tooltip:'Collapse all the objectives in the tree.',
//                cls:'x-btn-text-icon',
//                handler: function(){
//                    myTree.collapseAll();
//                }
//            },
    //            "-",
//            {
//                xtype:'button',
//                text:'Expand Objective',
//                icon:DeutscheBank.imgPath+'arrow_branch.png',
//                cls:'x-btn-text-icon',
//                tooltip:'Shows an expanded view of the selected objective',
//                handler: function(){
//                    var myTree = Ext.getCmp("myTree" + DeutscheBank.prefix);
//                    var selModel = myTree.getSelectionModel();
//    console.log("selModel (expend node):",selModel);
//                    if(selModel){
//                        //Expand this node
//                        var node = selModel.selNode;
//
//                        if(node){
//                            node.expand(false,true); //[Boolean deep], [Boolean anim], [Function callback]
//                        }
//                        else{
//                            DeutscheBank.mask("Please select an objective", 2000, true)
//                        }
//    //console.log("Node:", node)
//
//                    }
//                }
//            },
                "-",
            {
                xtype:'button',
                text:'Refresh Tree',
                icon:DeutscheBank.imgPath+'page_refresh.png',
                tooltip:'Refresh the tree view to show the most updated data.',
                cls:'x-btn-text-icon',
                handler: function(){

                    //Clear ActiveNode so that the tree renders collapsed.
                    DeutscheBank.activeNode = "";

                    //Clear PeersMode
                    DeutscheBank.peersModeOff = false;
                    
                    DeutscheBank.updateTree();

                    DeutscheBank.mask(" Updating tree view, please wait...", 4000);
                }
            },   "-",
            {
                    xtype:'button',
                    text:'Help',
                    icon:DeutscheBank.imgPath +'help.png',
                    cls:'x-btn-text-icon',
                    tooltip:'Click this button to open the help file',
                    handler: function(){
                        window.open( DeutscheBank.helpURL)
                    }
                }
            ],
            items:[
                myTree
            ]
        })

        treeContainerPanel.render("treePanel" + DeutscheBank.prefix);
    }


    //Panel exists
    else{
        
       treeContainerPanelExists.add(myTree);

        treeContainerPanelExists.doLayout();
    }

    //If Question 2, then expand nodes
    if(expandNodes){
        root.expandChildNodes(true);
    }


    //Show the tree as in the previous state before reloading.
    if(DeutscheBank.activeNode){

        var myTree = Ext.getCmp("myTree"+DeutscheBank.prefix);
        var myRoot = myTree.getRootNode();


///THIS WORKS
        var data = root.childNodes


        for(var i=0; i< data.length; i++){

            var node = data[i];
//console.log("Child Node en ACtiveNode:", DeutscheBank.activeNode, " :: ", "node.attributes.attributes.objective_id:", node.attributes.attributes.objective_id);

//console.log("node.attributes.attributes.objective_id: ",node.attributes.attributes.objective_id, " :: DeutscheBank.activeNode.branchObjectiveId:", DeutscheBank.activeNode.branchObjectiveId)

            //Case if the Objective_id  == the branchObjectiveId from ActiveNode
            if(node.attributes.attributes.objective_id == DeutscheBank.activeNode.branchObjectiveId){
                //Then this is the node I need to expand.
                node.expand(true);

                break;
            }

            //Case where the objective_id == the master_id of one of the root nodes.
            if(node.attributes.attributes.objective_id == DeutscheBank.activeNode.attributes.attributes.master_id){
                //Then this is the node I need to expand.
                node.expand(true);

                break;
            }
        }

    }


    //Set Options to combos
    yearCombo.setValue("all");

    //Now Render Graph   (Check the display on the HTML on top of this file to shoe the td where the graph renders and uncomment/check func for iterating on tree)
    //    DeutscheBank.renderGraph();
}



DeutscheBank.deleteObjectiveNode = function(nodeSelected){
console.log("Node to delete: ", nodeSelected)

    if( nodeSelected){

        //In order to delete... Check that the user is the current user is the same as in setBy.
        if( DeutscheBank.user == nodeSelected.attributes.attributes.set_by){

            //If its the root node
            if( nodeSelected.id.indexOf("root") != -1){
                //Then its the root node
                DeutscheBank.mask("You can't erase the root node",2000, true)
            }

            else{
                //Check if this node has subObjectives, if it does not, then it can be erased.
                if(nodeSelected.attributes.children){
                    console.log("Has Children, cant delete node...")

                    DeutscheBank.mask("You can't delete an objective that contains sub objectives, please erase sub objectives first",5000, true)
                }
                else{

                    var objectiveId = nodeSelected.attributes.attributes.objective_id;

                    var dataObj = {
                        sid: "dbDeleteObjective",
                        oid:"invoke",
                        params: {
                            objective_id : objectiveId
                        }
                    }

                    console.log("dataObj:", dataObj);
                    DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.updateTree() );

                    DeutscheBank.mask("Erasing objective...",2000, true);
                }
            }

        }

        //User is != from current user, so Can't delete
        else{
            DeutscheBank.mask("Can not delete this objective, you may only delete objectives set by you",4000, true)            
        }


    }

    //Node is not selected
    else{

        DeutscheBank.mask("Please select an objective to delete",2000, true)        
    }
}


DeutscheBank.getDeutscheFormWindow = function(formType, attr){  //formType can be: 'detail', 'new', 'clone'.

    var rightColStyle="background-color:yellow";

    var fieldsWidth = 230;
    var textFieldCSS = "background:#ffCC66";
    var textFieldDisableCSS = "background:#E6E6E6";
    

    var categoriesCombo = DeutscheBank.getCategoriesComboBox("detailView");
    var setByCombo = DeutscheBank.getPeopleComboBox("set_by", "Set By");
    var setForCombo = DeutscheBank.getPeopleComboBox("set_for", "Set For");
    var privateCombo = DeutscheBank.getYesNoComboBox("private","Private"); //prefix,fieldLabel
//            console.log("catCombo for Id:", categoriesCombo);

    var formElementsArray = ""

    //New Objective Window (almost empty)
    if(formType == "new"){

        formElementsArray = [
            {
                xtype:'textfield', fieldLabel:'Objective Summary', name:'objective_summary', value:'' , style: textFieldCSS, allowBlank:false
            },
            {
                xtype:'textfield', fieldLabel:'Objective ID', value:'' , name:'objective_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },

            {
                xtype:'textfield', fieldLabel:'Year', name:'year', value:'' , style: textFieldCSS, allowBlank:false, vtype:'year'
            },
                setByCombo,
                setForCombo,
                categoriesCombo,
            {                                                    //Prepopulate with userName
                xtype:'textfield', fieldLabel:'Inserted By', name:'inserted_by', value: DeutscheBank.userName, disabled:true//readOnly:true, style:textFieldDisableCSS, allowBlank:false
            },
            {                                                                //Prepopulate with userName
                xtype:'textfield', fieldLabel:'Updated By', name:'updated_by', value: DeutscheBank.userName, disabled:true//readOnly:true, style:textFieldDisableCSS, allowBlank:false
            },

                //Here were the Date fields

                privateCombo,

            {
                xtype:'textfield', fieldLabel:'Master ID', value:'' , name:'master_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },
            {
                xtype:'textarea', fieldLabel:'Objective Details', name:'objective_details',value:'' , style: textFieldCSS, allowBlank:false
            }

        ]
    }

    //New Objective Window (inherit values)
    else if(formType == "newAmend"){ 

        formElementsArray = [
            {
                xtype:'textfield', fieldLabel:'Objective Summary', name:'objective_summary', value:attr.objective_summary , style: textFieldCSS, allowBlank:false
            },
            {
                xtype:'textfield', fieldLabel:'Objective ID', value:'' , name:'objective_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },

            {
                xtype:'textfield', fieldLabel:'Year', name:'year', value:attr.year , style: textFieldCSS, allowBlank:false, vtype:'year'
            },
                setByCombo,
                setForCombo,
                categoriesCombo,
            {                                                    //Prepopulate with userName
                xtype:'textfield', fieldLabel:'Inserted By', name:'inserted_by', value: DeutscheBank.userName,  disabled:true//readOnly:true,style:textFieldDisableCSS, allowBlank:false
            },
            {                                                                //Prepopulate with userName
                xtype:'textfield', fieldLabel:'Updated By', name:'updated_by', value: DeutscheBank.userName, disabled:true//readOnly:true, style:textFieldDisableCSS, allowBlank:false
            },

                //Here were the Date fields

                privateCombo,
            {
                xtype:'textfield', fieldLabel:'Master ID', value:'' , name:'master_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },

            {
                xtype:'textarea', fieldLabel:'Objective Details', name:'objective_details',value: attr.objective_details , style: textFieldCSS, allowBlank:false
            }

        ]
    }

    //Detials Window
    else if(formType=="detail"){
//console.log("USING NEW ARCHI TO GET FORM WINDOW");
        formElementsArray = [
            {
                xtype:'textfield', fieldLabel:'Objective Summary', name:'objective_summary', value: attr.objective_summary,style: textFieldCSS, allowBlank:false
            },
            {
                xtype:'textfield', fieldLabel:'Objective ID', value: attr.objective_id, name:'objective_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },

            {
                xtype:'textfield', fieldLabel:'Year', name:'year', value: attr.year, style: textFieldCSS, allowBlank:false, vtype:'year'
            },
                setByCombo,
                setForCombo,
                categoriesCombo,
            {
                xtype:'textfield', fieldLabel:'Inserted By', name:'inserted_by', value: attr.inserted_by, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
            {
                xtype:'textfield', fieldLabel:'Updated By', name:'updated_by', value: attr.updated_by, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
            {
                xtype:'textfield', fieldLabel:'Date Inserted', name:'date_inserted', value:attr.date_inserted, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
            {
               xtype:'textfield', fieldLabel:'Date Accepted', name:'date_accepted', value:attr.date_accepted, disabled:true//readOnly:true, style:textFieldDisableCSS
            },

            {
                xtype:'textfield', fieldLabel:'Date last updated', name:'date_last_updated', value:attr.date_last_updated, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
                privateCombo,

            {
                xtype:'textfield', fieldLabel:'Master ID', value: attr.master_id, name:'master_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },
            {
                xtype:'textarea', fieldLabel:'Objective Details', name:'objective_details',value: attr.objective_details, style: textFieldCSS, allowBlank:false
            }

        ]
    }
    //Clone Window
    else if(formType == "clone"){
//console.log("USING NEW ARCHI TO GET FORM WINDOW");
        formElementsArray = [
            {
                xtype:'textfield', fieldLabel:'Objective Summary', name:'objective_summary', value: attr.objective_summary,style: textFieldCSS, allowBlank:false
            },
            {
                xtype:'textfield', fieldLabel:'Objective ID', value: attr.objective_id, name:'objective_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },

            {
                xtype:'textfield', fieldLabel:'Year', name:'year', value: attr.year, style: textFieldCSS, allowBlank:false
            },
                setByCombo,
                setForCombo,
                categoriesCombo,
            {
                xtype:'textfield', fieldLabel:'Inserted By', name:'inserted_by', value: DeutscheBank.userName, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
            {                                                                   //Here we set the value of the current  user to Updated by
                xtype:'textfield', fieldLabel:'Updated By', name:'updated_by', value: DeutscheBank.userName, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
            {
                xtype:'textfield', fieldLabel:'Date Inserted', name:'date_inserted', value:attr.date_inserted, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
            {
               xtype:'textfield', fieldLabel:'Date Accepted', name:'date_accepted', value:attr.date_accepted, disabled:true//readOnly:true, style:textFieldDisableCSS
            },

            {
                xtype:'textfield', fieldLabel:'Date last updated', name:'date_last_updated', value:attr.date_last_updated, disabled:true//readOnly:true, style:textFieldDisableCSS
            },
                privateCombo,

            {
                xtype:'textfield', fieldLabel:'Master ID', value: attr.master_id, name:'master_id', hidden:true, hideLabel:true, readOnly:true, style: textFieldCSS
            },
            {
                xtype:'textarea', fieldLabel:'Objective Details', name:'objective_details',value: attr.objective_details, style: textFieldCSS, allowBlank:false
            }

        ]
    }

    var panel = new Ext.form.FormPanel({
        id:formType + DeutscheBank.prefix, //'detailsPanel' + DeutscheBank.prefix,
        frame:true,
        defaults:{
            width: fieldsWidth
        },
        /**
          * objective_id (hidden)
          * master_id (hidden)
          * year
          * set_by
          * set_for
          * category_id
          * objective_summary
          * objective_details
          * date_accepted
          * master_id (hidden)
          * private_objective
          * date_inserted
          * inserted_by
          * date_last_updated
          * updated_by
          *
         */
        items: formElementsArray
    });

    return panel;
    
}


DeutscheBank.getActiveNodeData = function(node){

    DeutscheBank.activeNode = node;

    DeutscheBank.activeNode.branchObjectiveId = "";

    node.bubble(function(node){
//        console.log("This is the node in bubble when activeNode: ", node );

        var id = node.id;

        if( id.indexOf("root") == -1){
            //Is not the root
            var objective_id = node.attributes.attributes.objective_id;

            DeutscheBank.activeNode.branchObjectiveId = objective_id;
        }
    })
//    console.log("Este es el obj id del branch que voy a expandir: ", DeutscheBank.activeNode.branchObjectiveId);
     
}


DeutscheBank.showNodeDetailsWindow = function(node, e){
//function dblClickNode( node, e){

    //Active Node
    DeutscheBank.getActiveNodeData(node);

    //Roles
    if(DeutscheBank.userRole == "normal"){

        var userCanSeeDetails = DeutscheBank.rolesNormalEditObjective(node);

        if(!userCanSeeDetails){
    
            DeutscheBank.mask("Sorry you are not entitled to view this objective details. ","3000",true);

            return;
        }
    }


console.log("Showing details...", node);
//console.log("node path: ",node.getPath());

    var attr = node.attributes.attributes;

    var deutscheForm = DeutscheBank.getDeutscheFormWindow("detail", attr);  //Attributes, type_of_Window (detail, new, clone)


    //I need to override the value for the combos, since Ext dont get the combo values with: getForm().getValues() /Americo
    var setByCombo = Ext.getCmp("personCombo"+"set_by"+ DeutscheBank.prefix);
    var setForCombo = Ext.getCmp("personCombo"+"set_for"+ DeutscheBank.prefix);
    var categoriesCombo = Ext.getCmp('categoriesCombo' + "detailView" + DeutscheBank.prefix);
    var privateCombo = Ext.getCmp('yesNoCombo' + "private" + DeutscheBank.prefix);

    var combosObj ={
        setByCombo : setByCombo,
        setForCombo: setForCombo,
        categoriesCombo: categoriesCombo,
        privateCombo : privateCombo
    }

    var detailsWindow = new Ext.Window({
        width: DeutscheBank.dbFormWidth, //380,
        height:DeutscheBank.dbFormHeight, //455,
//                contentEl:'loginWindow'+ DeutscheBank.prefix,
//                constrain:true,
        modal:true,
        id:'detailWindow' + DeutscheBank.prefix,
        resizable:true,
        autoScroll: true,
        shadow:false,
        title:'Objective Details',
        tbar:[
//        {
//            xtype:'button',
//            text:'Save',
//            tooltip:'Save detail data of this objective',
//            icon:DeutscheBank.imgPath+'accept.png',
//            cls:'x-btn-text-icon',
//            handler: function(){
//                DeutscheBank.saveNodeDetails(combosObj);
//            }
//
//        }, "-",
        {
            xtype:'button',
            text:'Save & Close',
            tooltip:'Save the objectives details data and close this window.',
            icon:DeutscheBank.imgPath+'application_go.png',
            cls:'x-btn-text-icon',
            handler: function(){
                DeutscheBank.saveNodeDetails(combosObj, true); //True param is for closing this window
            }
        },
            "-",
//        {
//            xtype:'button',
//            text:'Clone',
//            tooltip:'Clone this objective',
//            icon:DeutscheBank.imgPath+'application_double.png',
//            cls:'x-btn-text-icon',
//            handler: function(){
//                DeutscheBank.showCloneNodeWindow(attr, node);   //attr is where all the data is saved
//            }
//        }, "-",
        {
            xtype:'button',
            text:'Close',
            icon:DeutscheBank.imgPath+'cancel.png',
            cls:'x-btn-text-icon',
            handler: function(){
                DeutscheBank.showGraph();
                detailsWindow.close();
            }
        }
        ],
        items:[
            deutscheForm
        ]
    });

    detailsWindow.setPosition(40,50);                   
    detailsWindow.show();

    //Set Options to Combos
    setByCombo.setValue(attr.set_by);
    setForCombo.setValue(attr.set_for);
    categoriesCombo.setValue(attr.category_id);
    privateCombo.setValue(attr.private_objective);

    //Roles
    if( DeutscheBank.userRole == "normal"){

        var setOfObjs ={};

        setOfObjs.privateCombo = privateCombo;
        setOfObjs.node = node;

        DeutscheBank.rolesNormalPrivateCombo( setOfObjs);

    }

}

DeutscheBank.getDeutscheActionWindow = function( nodeSelected){

    
    var formElementsArray ="";

    formElementsArray = [
        {   //Number  1 of Requirements: Root Objective
            xtype:'button',
            text: 'Create a new Master Objective',
            tooltip:"Creates a new root Master Objective <br>(NOTE: Only certain roles have access to this function)",
            id:'masterObjective' + DeutscheBank.prefix,
            icon:DeutscheBank.imgPath+'application_key.png',
            cls:'x-btn-text-icon',
            handler:function(){

                var actionWindow = Ext.getCmp('actionWindow' + DeutscheBank.prefix);

                actionWindow.close();

                DeutscheBank.showNewObjectiveWindow( nodeSelected)

            }
        },
        { html: "&nbsp"},

        {   //Number  2 of Requirements: Clone
            xtype:'button',
            text: 'Clone and modify this Objective',
            tooltip:"Clones the selected objective and <br>allows the user to change its details",
            id:'cloneObjective' + DeutscheBank.prefix,
            icon:DeutscheBank.imgPath+'application_double.png',
            cls:'x-btn-text-icon',
            handler:function(){

                var actionWindow = Ext.getCmp('actionWindow' + DeutscheBank.prefix);

                actionWindow.close();

                var attr = nodeSelected.attributes.attributes;

                DeutscheBank.showCloneNodeWindow(attr, nodeSelected)     

            }
        },
        { html: "&nbsp"},

        {   //Number  3 of Requirements: Clone and add as subojective
            xtype:'button',
            text: 'Create a new Child Objective ',
            tooltip:"Creates a new child objective <br>under the selected objective",
            id:'subObjective' + DeutscheBank.prefix,
            icon:DeutscheBank.imgPath+'application_go.png',
            cls:'x-btn-text-icon',
            handler:function(){

                var actionWindow = Ext.getCmp('actionWindow' + DeutscheBank.prefix);

                actionWindow.close();

                DeutscheBank.showNewObjectiveWindow( nodeSelected)

            }
        }
    ]


    var panel = new Ext.form.FormPanel({
        id:'actionPanel' + DeutscheBank.prefix, //'detailsPanel' + DeutscheBank.prefix,
        frame:true,
        defaults:{
        },
        
        items: formElementsArray
    });

    return panel;

}

DeutscheBank.showActionWindow = function( nodeSelected){

    var deutscheForm = DeutscheBank.getDeutscheActionWindow( nodeSelected);

    var widthFF = 235;
    var heightFF = 150;

    if(Ext.isIE){
        widthFF=300;
        heightFF= 150;
    }

    var newWindow = new Ext.Window({
        width: widthFF,
        height: heightFF,
//                contentEl:'loginWindow'+ DeutscheBank.prefix,
//                constrain:true,
        modal:true,
        id:'actionWindow' + DeutscheBank.prefix,
        resizable:true,
        autoScroll: true,
        shadow:false,
        title:'New...',
        items:[
            deutscheForm
        ]
    });

    // Disabled/Enabled Buttons

    var masterObjectiveBtn = Ext.getCmp("masterObjective" + DeutscheBank.prefix);
    var cloneObjectiveBtn = Ext.getCmp("cloneObjective" + DeutscheBank.prefix);
    var subObjectiveBtn = Ext.getCmp("subObjective" + DeutscheBank.prefix);

        //If no node is selected or root is selected: then disabled: #2 and #3.
        if(!nodeSelected || DeutscheBank.isRootNodeSelected( nodeSelected) ){
            cloneObjectiveBtn.disable();
            subObjectiveBtn.disable();
        }
        //If any node but root is selected: disable #1
        else if(nodeSelected){
            masterObjectiveBtn.disable();    
        }

        //if Role != topdog, then #1 is disabled
        if (DeutscheBank.userRole != "topdog"){
            masterObjectiveBtn.disable();            
        }


    newWindow.setPosition(130,225);
    newWindow.show();

}


DeutscheBank.showNewObjectiveWindow = function( nodeSelected){

    //Active Node
    DeutscheBank.getActiveNodeData(nodeSelected);


    var deutscheForm ="";

   if(nodeSelected){
        //Adding an objective to an existing one
        var attr = nodeSelected.attributes.attributes;
        
        deutscheForm = DeutscheBank.getDeutscheFormWindow("newAmend", attr);  //Attributes, type_of_Window (detail, new, clone)
    }
    else{
        //Master Objective
        deutscheForm = DeutscheBank.getDeutscheFormWindow("new");  //Attributes, type_of_Window (detail, new, clone)
    }



    var setByCombo = Ext.getCmp("personCombo"+"set_by"+ DeutscheBank.prefix);
    var setForCombo = Ext.getCmp("personCombo"+"set_for"+ DeutscheBank.prefix);
    var categoriesCombo = Ext.getCmp('categoriesCombo' + "detailView" + DeutscheBank.prefix);
    var privateCombo = Ext.getCmp('yesNoCombo' + "private" + DeutscheBank.prefix);

    var combosObj ={
        setByCombo : setByCombo,
        setForCombo: setForCombo,
        categoriesCombo: categoriesCombo,
        privateCombo : privateCombo
    }

    var newWindow = new Ext.Window({
        width:385,
        height:390,
//                contentEl:'loginWindow'+ DeutscheBank.prefix,
//                constrain:true,
        modal:true,
        id:'newWindow' + DeutscheBank.prefix,
        resizable:true,
        autoScroll: true,
        shadow:false,
        title:'New Objective',
        tbar:[{
            xtype:'button',
            text:'Save & Close',
            tooltip:'Save the new objective and close this window',
            icon:DeutscheBank.imgPath+'application_go.png',
            cls:'x-btn-text-icon',
            handler: function(){
                DeutscheBank.saveNewObjective( combosObj, nodeSelected);
            }

        }, "-",
        {
            xtype:'button',
            text:'Close',
            icon:DeutscheBank.imgPath+'cancel.png',
            cls:'x-btn-text-icon',
            handler: function(){
                DeutscheBank.showGraph();
                newWindow.close();
            }
        }],
        items:[
            deutscheForm
        ]
    });

    //Set Options to combos
    privateCombo.setValue("n"); //Default to No Private
    setByCombo.setValue( DeutscheBank.user) //DEfault to current user


    //ROLES PERMISSION
    if( DeutscheBank.userRole == "normal"){

        var setOfObjs ={};

        setOfObjs.privateCombo = privateCombo;
        setOfObjs.node = nodeSelected;

        DeutscheBank.rolesNormalPrivateCombo( setOfObjs);

        //This means if user is normal, but he is amending an objective, then private is enable
        if(nodeSelected){
            privateCombo.enable();
        }

    }

    //If nodeSelected, then inherit: obj summary, Year, Category and obj Details (only category is being set here, the rest in the getDeutscheFormWindow
    if(nodeSelected){

        categoriesCombo.setValue( nodeSelected.attributes.attributes.category_id);
        

    }

    //OPTIONS DISABLED IF NEW ROOT OBJECTIVE
    if( !nodeSelected || DeutscheBank.isRootNodeSelected(nodeSelected) ){
        //Then is a masterObjective: set_by, set_for --> current user and disabled
        //Private default to N and disabled
        setForCombo.setValue( DeutscheBank.user) //DEfault to current user

        setByCombo.disable();
        setForCombo.disable();

        privateCombo.disable();
    }
    //OPTIONS DISABLED IF NEW SUB OBJECTIVE
    else if(nodeSelected){

        //set by must default to set for from selected record and cannot be changed        
        setByCombo.setValue( nodeSelected.attributes.attributes.set_for )
        setByCombo.disable();

        //private must default to no but can be changed
//            privateCombo.disable();
    }


    newWindow.setPosition(40,50);
    newWindow.show();

//    }


}

DeutscheBank.isRootNodeSelected = function( nodeSelected){

    var result = false;

    if( nodeSelected){

        //Check if the nodeSelected is the root node, if it is then set nodeSelected as empty.
        if(nodeSelected.id.indexOf("root") != -1){
            result = true;
        }
    }

    return result;
}


DeutscheBank.saveNewObjective = function( combosObj, nodeSelected){

    var objectiveId = "";

    //If no nodeSelected, then there is no Objective ID, the DB will generate one.
    if(nodeSelected){

        //Check if the nodeSelected is the root node, if it is then set nodeSelected as empty.
        if(nodeSelected.id.indexOf("root") != -1){
            nodeSelected = null;
        }
        //normal case for node selected.
        else{
            objectiveId = nodeSelected.attributes.attributes.objective_id;    
        }


    }

    var panel = "";

    if(nodeSelected){
        panel = Ext.getCmp('newAmend' + DeutscheBank.prefix);        
    }
    else{
        panel = Ext.getCmp('new' + DeutscheBank.prefix);
    }



    
    //Validate PAnel
    var panelValid = panel.getForm().isValid();

    if(!panelValid){

        if(Ext.isIE){

            var theWindow = Ext.getCmp('newWindow' + DeutscheBank.prefix);
            theWindow.hide();

            DeutscheBank.mask("The Form is not complete or contains errors, please verify the fields before saving", 3200, true);

            setTimeout(unMaskBody, 3200);

            function unMaskBody(){

                theWindow.show();
            }
        }
        else{
            DeutscheBank.mask("The Form is not complete or contains errors, please verify the fields before saving", 3200, true);
        }



        return;
    }

    var formValues = panel.getForm().getValues();

    formValues.set_by = combosObj.setByCombo.getValue();
    formValues.set_for = combosObj.setForCombo.getValue();
    formValues.category_id = combosObj.categoriesCombo.getValue();
    formValues.private_objective = combosObj.privateCombo.getValue();

console.log("Valores de Forma:", formValues);

    var dataObj = {};

    if(nodeSelected){
        //SubObjective

        dataObj = {
        sid: "dbAddNewObjective",
        oid:"invoke",
        params: {
            year: formValues.year,
            set_by: formValues.set_by,
            set_for: formValues.set_for,
            category_id: formValues.category_id,
            objective_summary: formValues.objective_summary,
            objective_details: formValues.objective_details,
            master_id: objectiveId,  //This is the difference with the else case
            private_objective: formValues.private_objective,
            inserted_by: formValues.inserted_by,
            updated_by: formValues.updated_by
        }
    }
    }
    else{
        //Main Objective
        dataObj = {
        sid: "dbAddNewObjective",
        oid:"invoke",
        params: {
            year: formValues.year,
            set_by: formValues.set_by,
            set_for: formValues.set_for,
            category_id: formValues.category_id,
            objective_summary: formValues.objective_summary,
            objective_details: formValues.objective_details,
            //No master ID is sent since this is a root objective node (on the mashup I am setting default to "").
            private_objective: formValues.private_objective,
            inserted_by: formValues.inserted_by,
            updated_by: formValues.updated_by
        }
    }
    }



    console.log("dataObj:", dataObj);
    DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.dataSavedSuccessfully);

    var newWindow = Ext.getCmp('newWindow' + DeutscheBank.prefix);
    newWindow.destroy();

//    DeutscheBank.updateTree();   //Update will be done on dataSavedSuccessfully function
}


DeutscheBank.saveNodeDetails = function(combosObj, closeWindow){

    var panel = Ext.getCmp('detail' + DeutscheBank.prefix);

    //Validate PAnel
    var panelValid = panel.getForm().isValid();

    if(!panelValid){

        //Special case where SetFor and Setby are the same, let them through...
        if(combosObj.setByCombo.getValue() == combosObj.setForCombo.getValue()){
          //Let them through... 
        }
        else{
            DeutscheBank.mask("The Form is not complete or contains errors, please correct before saving", 3200, true);

            return;
        }
    }


    var formValues = panel.getForm().getValues()
    console.log("Valores de Forma:", formValues);

    formValues.set_by = combosObj.setByCombo.getValue();
    formValues.set_for = combosObj.setForCombo.getValue();
    formValues.category_id = combosObj.categoriesCombo.getValue();
    formValues.private_objective = combosObj.privateCombo.getValue();
    console.log("Valores de Forma:", formValues);

    //Create Obj to send to mashup and save data on DB.
    var dataObj = {
        sid: "dbUpdateObjective",
        oid:"invoke",
        params: {
            objective_id : formValues.objective_id,
            year: formValues.year,
            set_by: formValues.set_by,
            set_for: formValues.set_for,
            category_id: formValues.category_id,
            objective_summary: formValues.objective_summary,
            objective_details: formValues.objective_details,
            date_accepted: formValues.date_accepted,
            master_id: formValues.master_id,
            private_objective: formValues.private_objective,
            date_inserted: "",//formValues.date_inserted,
            inserted_by: formValues.inserted_by,
            date_last_updated: "",//formValues.date_last_updated,
            updated_by: formValues.updated_by
        }
    }

    console.log("dataObj:", dataObj);
    DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.dataSavedSuccessfully);

    if(closeWindow){
        DeutscheBank.destroyNodeDetailsWindow();
    }
    

//    DeutscheBank.updateTree(); //Will be donde on dataSavedSuccessfully

}


DeutscheBank.destroyNodeDetailsWindow = function(){

    var nodeDetailsWin = Ext.getCmp('detailWindow' + DeutscheBank.prefix);

    if(nodeDetailsWin){

        nodeDetailsWin.destroy();
    }
}

/*
This is the rule for private combos when the userRole is normal
 */
DeutscheBank.rolesNormalPrivateCombo = function( setOfObjs){

    //PRIVATE COMBO
    var privateCombo = setOfObjs.privateCombo;
    var node = setOfObjs.node; //If node is undefined, then no node was selected, else a node is selected.

    if(node){
        //Check to see if the node has as parent the root node (Then this node is a root objective)
        var parentNodeId = node.parentNode.id;

        if(parentNodeId.indexOf("root") >= 0){
console.log("...Trying to edit a root node when userRole is normal")            
            //Its the root node, so the private combo will be set to yes.
            privateCombo.setValue("n"); //Default to No Private
            privateCombo.disable();
        }

        //Else, This means that a normal user can add both public and private subobjectives.
        else{
            //Default options
        }
    }
    else{
        privateCombo.setValue("y"); //Default to No Private
        privateCombo.disable();
    }


}

/*
This rules is for specifing that normal roles can only edit an objective, if set_by == userName
 */
DeutscheBank.rolesNormalEditObjective = function(node){

    var set_by = node.attributes.attributes.set_by; //this is the user id, not the username
    var set_for= node.attributes.attributes.set_for; //this is the user id, not the username

    if(set_by == DeutscheBank.user || set_for == DeutscheBank.user){

       return true; //This means that he can see the edit window
    }
    else{
        return false;
    }

}

DeutscheBank.dataSavedSuccessfully = function( response){

    console.log("Inside Data Saved Successfully...");

    DeutscheBank.updateTree();

    DeutscheBank.mask(" Saving...");

}

DeutscheBank.showCloneNodeWindow = function(attr, node){
    
    //Active Node
    DeutscheBank.getActiveNodeData(node);

    //Hide Objective Details window.
//    var detailWindow = Ext.getCmp('detailWindow' + DeutscheBank.prefix);
//    detailWindow.destroy();

//    var attr = node.attributes.attributes;

    var deutscheForm = DeutscheBank.getDeutscheFormWindow("clone", attr);  //Attributes, type_of_Window (detail, new, clone)


    //I need to override the value for the combos, since Ext dont get the combo values with: getForm().getValues() /Americo
    var setByCombo = Ext.getCmp("personCombo"+"set_by"+ DeutscheBank.prefix);
    var setForCombo = Ext.getCmp("personCombo"+"set_for"+ DeutscheBank.prefix);
    var categoriesCombo = Ext.getCmp('categoriesCombo' + "detailView" + DeutscheBank.prefix);
    var privateCombo = Ext.getCmp('yesNoCombo' + "private" + DeutscheBank.prefix);

    var combosObj ={
        setByCombo : setByCombo,
        setForCombo: setForCombo,
        categoriesCombo: categoriesCombo,
        privateCombo : privateCombo
    }

    var cloneWindow = new Ext.Window({
        width:DeutscheBank.dbFormWidth,
        height: DeutscheBank.dbFormHeight,
//                contentEl:'loginWindow'+ DeutscheBank.prefix,
//                constrain:true,
        modal:true,
        id:'cloneWindow' + DeutscheBank.prefix,
        resizable:true,
        autoScroll: true,
        shadow:false,
        title:'Clone Objective ',
        tbar:[
        {
            xtype:'button',
            text:'Save Clone',
            tooltip:'Saves this clone objective',
            icon:DeutscheBank.imgPath+'accept.png',
            cls:'x-btn-text-icon',
            handler: function(){
                DeutscheBank.saveCloneNode(combosObj);
            }

        }, "-",

//        {
//            xtype:'button',
//            text:'Save Clone as Sub Objective',
//            tooltip:'Saves this clone objective as a sub objective of the selected node',
//            icon:DeutscheBank.imgPath+'application_double.png',
//            cls:'x-btn-text-icon',
//            handler: function(){
//                DeutscheBank.saveCloneNode(combosObj, true);
//            }
//
//        }, "-",

        {
            xtype:'button',
            text:'Close',
            icon:DeutscheBank.imgPath+'cancel.png',
            cls:'x-btn-text-icon',
            handler: function(){

                cloneWindow.close();
            }
        }],
        items:[
            deutscheForm
        ]
    });

    cloneWindow.setPosition(40,50);
    cloneWindow.show();

    //Set Options to Combos
    setByCombo.setValue( DeutscheBank.user);  //Setting the user that is login
    setByCombo.disable();

    privateCombo.setValue("n");
    privateCombo.disable();

    categoriesCombo.setValue(attr.category_id);


    //Roles (Deprecated since new action window)
//    if( DeutscheBank.userRole == "normal"){
//
//        var setOfObjs ={};
//
//        setOfObjs.privateCombo = privateCombo;
//        setOfObjs.node = node;
//
//        DeutscheBank.rolesNormalPrivateCombo( setOfObjs);
//
//    }
};


DeutscheBank.saveCloneNode = function(combosObj, asSubObjective){
console.log("Entreee a SAVE CLONE NODE")
    var cloneWindow = Ext.getCmp('cloneWindow' + DeutscheBank.prefix);


//    Ext.MessageBox.alert("Clone Node", "The node was successfully cloned");

    //Ok So now lets Save the clone
    var panel = Ext.getCmp('clone' + DeutscheBank.prefix);


    //Validate PAnel
    var panelValid = panel.getForm().isValid();

    if(!panelValid){

        DeutscheBank.mask("The Form is not complete or contains errors, please correct before saving", 3200, true);

        return;
    }

    var formValues = panel.getForm().getValues()
//console.log("Valores de Forma:", formValues);

    formValues.set_by = combosObj.setByCombo.getValue();
    formValues.set_for = combosObj.setForCombo.getValue();
    formValues.category_id = combosObj.categoriesCombo.getValue();
    formValues.private_objective = combosObj.privateCombo.getValue();
console.log("Valores Forma Clone:", formValues);


    var dataObj = {};

    if( asSubObjective){
        dataObj = {
            sid: "dbAddNewObjective",
            oid:"invoke",
            params: {
                year: formValues.year,
                set_by: formValues.set_by,
                set_for: formValues.set_for,
                category_id: formValues.category_id,
                objective_summary: formValues.objective_summary,
                objective_details: formValues.objective_details,
                master_id: formValues.objective_id,
                private_objective: formValues.private_objective,
                inserted_by: formValues.inserted_by,
                updated_by: formValues.updated_by
            }
        }
    }
    else{
        dataObj = {
            sid: "dbAddNewObjective",
            oid:"invoke",
            params: {
                year: formValues.year,
                set_by: formValues.set_by,
                set_for: formValues.set_for,
                category_id: formValues.category_id,
                objective_summary: formValues.objective_summary,
                objective_details: formValues.objective_details,
                master_id: formValues.master_id,
                private_objective: formValues.private_objective,
                inserted_by: formValues.inserted_by,
                updated_by: formValues.updated_by
            }
        }
    }


    console.log("dataObj:", dataObj);
    DeutscheBank.getDataFromPresto(dataObj, DeutscheBank.dataSavedSuccessfully);

    cloneWindow.destroy();

//    DeutscheBank.updateTree(); //Will be done on dataSavedSuccessfully
    
};



DeutscheBank.renderGraph = function(){

    //If graph already exists, delete it and render it again.
    var graphExists = document.getElementById("ChartId");

    if(graphExists){

        var parent = graphExists.parentNode;

        parent.removeChild(graphExists);

        parent.innerHTML= "";
    }

    var treeInString = DeutscheBank.traverseTree();
//console.log("TreeInString: ", treeInString)

    var chart = new FusionCharts("http://64.34.161.56:8081/mashlets/DB_PMO/charts/MultiLevelPie.swf", "ChartId", "500", "400", "0", "1");
//   var chart = new FusionCharts("./charts/MultiLevelPie.swf", "ChartId", "500", "400", "0", "1");
    chart.setDataXML( treeInString );
//    chart.setDataXML( graphContent)
    chart.append("graphPanel" + DeutscheBank.prefix);


};

/*
Function for Traversing the tree in order get the XML for the Pie Graph.
 */
/*
DeutscheBank.traverseTree = function(){

    var tree = Ext.getCmp('myTree' + DeutscheBank.prefix);

    var root = tree.getRootNode();

    var treeInXML = [
        "<chart palette='2' piefillAlpha='34' pieBorderThickness='3' hoverFillColor='FDCEDA' pieBorderColor='FFFFFF' baseFontSize='9' useHoverColor='1' caption='Pie View' >"
    ];

    //Create code for the Root
    treeInXML.push("<category label='"+root.text+"' fillColor='DBFF6C'>");

    var branchDepth = 0;
    var lastChild = root.lastChild
    //Here is where the tree is traverse
    root.cascade( function(node){
//console.log("Traverse of node:", node);//, " :: isLeaf:", node.isLeaf())
        
        //Random Color:
        var color = parseInt(Math.random().toString() * 1000000);

        //Formatting text node
        var text = node.text;
        var parentesis = text.indexOf("(");
        var formattedText = "";

        if( parentesis > 0){
            //There is (
            formattedText = text.substr(0, parentesis);
//            formattedText = text.substr(0, parentesis) + "\n" + text.substr(parentesis, text.length)
        }
        else{
            //There is not
            formattedText = text
        }
//console.log("formattedText:",formattedText)
        formattedText = formattedText.replace(/%/g, "");  

        //Node Attributes
        var attr = node.attributes.attributes;
        var descriptionText= [];

        if(node.id != root.id){
            descriptionText = [
                "Set For: ", attr.set_for,"\n",
                "Summary: ", attr.objective_summary,"\n",
                "Inserted: ", attr.date_inserted,"\n",
                "Updated By: ", attr.updated_by,"\n",
                "Year: ",attr.year
            ]
        }
        descriptionText = descriptionText.join("");
//console.log("DescriptionText:", descriptionText)

        //Add name below (based on customer review)
        if(attr){
            var setFor = attr.set_for;
            setFor = setFor.substring(0, setFor.indexOf("@"))
            formattedText = formattedText + "\n" + setFor;
        }                

        //If node is a branch
        if( node.firstChild && node.id != root.id){
//console.log("This NODE:"+ node+ " is a: BRANCHH" )
            treeInXML.push("<category label='"+ formattedText +"' fillColor='"+ color +"' hoverText='",descriptionText,"'>");
            branchDepth++;
        }

        //If node is leaf
        if( !node.firstChild ){
//console.log("This NODE:"+ node+ " is a: LEAFF" )            
            treeInXML.push("<category label='"+ formattedText +"' fillColor='"+ color +"' hoverText='",descriptionText,"'></category>");

            //Last child of its  parent
            if( node.isLast() ){
                treeInXML.push("</category>");

                //Add closes for all the depths
                for(var i = 1; i< branchDepth; i++){
                    treeInXML.push("</category>");
                }

                //If this leaf is from the last child of the root, then add an extra child (fuzzy logic)
                if(node.isAncestor(lastChild) ){
                    treeInXML.push("</category>");
                }

                branchDepth = 0;

            }
        }

    });

    //Close Root node
//    treeInXML.push("</category>");


    //End of the Graph Code
    treeInXML.push("<styles>")
    treeInXML.push("<definition>")
    treeInXML.push("<style name='myHTMLFont' type='font' isHTML='1' />")
    treeInXML.push("</definition>")
    treeInXML.push("<application>")
    treeInXML.push("<apply toObject='TOOLTIP' styles='myHTMLFont' />")
    treeInXML.push("</application>")
    treeInXML.push("</styles>")
    treeInXML.push("</chart>")


    return treeInXML.join("");

}
/*

 */
DeutscheBank.hideGraph = function(){

   var graphContainer = Ext.get("graphPanel" + DeutscheBank.prefix);

    graphContainer.hide();

};

DeutscheBank.showGraph = function(){

   var graphContainer = Ext.get("graphPanel" + DeutscheBank.prefix);

    graphContainer.show();

};

DeutscheBank.mask = function(text, secs, dontShowImage){

    if(!secs) secs = 2000;

    var mashletBody = Ext.get(DeutscheBank.instance.bodyEl)
//    var mashletBody = Ext.get("body" + DeutscheBank.prefix);

    if(dontShowImage){

        mashletBody.mask( text);
    }
    else{

        mashletBody.mask("<img src='"+DeutscheBank.imgPath+"ajax-loader.gif'>" +text);
    }
    setTimeout(unMaskBody, secs);


    function unMaskBody(){

        mashletBody.unmask();
    }

};

DeutscheBank.userDataNotFound = function(){

    DeutscheBank.mask("No information was found for user: " + DeutscheBank.user + ". Please verify the user and try again", 4000, true);

}


function getDeutscheBankUserName(){

    return DeutscheBank.activeUser.substr(0, DeutscheBank.activeUser.indexOf("@") );
}

